package kxfang.com.common.services;

import android.annotation.SuppressLint;
import android.app.Service;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.os.PowerManager;
import android.widget.Toast;

import com.blankj.utilcode.util.ApiUtils;
import com.orhanobut.hawk.Hawk;



import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import kxfang.com.base.livedatabus.LiveDatabus;
import kxfang.com.base.utils.GsonUtils;
import kxfang.com.common.bean.BlueBusEvent;
import kxfang.com.common.bean.OrderListDetailModel;
import kxfang.com.common.bean.PrintOrderInfo;
import kxfang.com.common.config.HttpConfig;
import kxfang.com.common.constant.Constant;
import kxfang.com.common.databus.MastEvent;
import kxfang.com.common.parameter.OrderPar;
import kxfang.com.common.utils.BluetoothUtil;
import kxfang.com.common.utils.PrintUtil;
import kxfang.com.http.EasyHttp;
import kxfang.com.http.callback.SimpleCallBack;
import kxfang.com.http.exception.ApiException;


/**
 * @author Administrator
 */
public class BluetoothService extends Service {

    /**
     * 标识服务如果被杀死之后的行为
     */
    int mStartMode;

    /**
     * 绑定的客户端接口
     */
    IBinder mBinder;

    /**
     * 标识是否可以使用onRebind
     */
    boolean mAllowRebind;

    private ThreadPoolExecutor poolExecutor;
    private boolean flag = false;

    String tag = getClass().getSimpleName();
    private static BluetoothSocket mSocket;
    private AsyncTask mConnectTask;
    private PrintOrderInfo orderInfo;

    private PrintOrderInfo tempInfo;

    private List<PrintOrderInfo> tempList = new ArrayList<>();

    private BluetoothDevice device = null;

    private OutputStream outputStream;

    /**
     * 蓝牙连接成功后回调，该方法在子线程执行，可执行耗时操作
     */
    protected void closeSocket() {
        if (mSocket != null) {
            try {
                mSocket.close();
            } catch (IOException e) {
                mSocket = null;
                e.printStackTrace();
            }
        }
    }

    protected void cancelConnectTask() {
        if (mConnectTask != null) {
            mConnectTask.cancel(true);
            mConnectTask = null;
        }
    }

//    private void initReceiver() {
//        poolExecutor = new ThreadPoolExecutor(3, Integer.MAX_VALUE, 1, TimeUnit.SECONDS,
//                new LinkedBlockingQueue<>(50), new MyThreadFactory("Bluetooth"));
//    }

    public void connectDevice(BluetoothDevice device, int taskType) {
        mConnectTask = new ConnectBluetoothTask(taskType).execute(device);
    }

    public void connectDevice(PrintOrderInfo info, PrintUtil.OnPrintResult result) {
        if (info != null) {
            OrderPar par = new OrderPar();
            par.setOrderNo(info.getParam().getID());
            EasyHttp.post(HttpConfig.getOrderDetail)
                    .cacheKey(HttpConfig.getOrderDetail)
                    .upJson(GsonUtils.toJson(par))
                    .execute(new SimpleCallBack<OrderListDetailModel>() {
                        @Override
                        public void onSuccess(OrderListDetailModel orderListDetailModel) {
                            PrintUtil.printTestT(mSocket, orderListDetailModel, result);
                        }

                        @Override
                        public void onError(ApiException e) {

                        }

                        @Override
                        public void onCompleted() {

                        }
                    });

        } else {
            result.onFinish("");
        }
    }

    class ConnectBluetoothTask extends AsyncTask<BluetoothDevice, Integer, BluetoothSocket> {

        int mTaskType;

        public ConnectBluetoothTask(int taskType) {
            this.mTaskType = taskType;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected BluetoothSocket doInBackground(BluetoothDevice... params) {
            if (mSocket != null && mSocket.isConnected()) {
                onConnected(mSocket, mTaskType);
                return mSocket;
            }
            mSocket = BluetoothUtil.connectDevice(params[0]);
            try {
                outputStream = mSocket.getOutputStream();
                sendHeart();
            } catch (IOException e) {
                e.printStackTrace();
            }
            onConnected(mSocket, mTaskType);
            return mSocket;
        }

        @Override
        protected void onPostExecute(BluetoothSocket socket) {
            if (socket == null || !socket.isConnected()) {
                toast("连接打印机失败");
            } else {
//                EventBus.getDefault().post(new BlueBusEvent());
                LiveDatabus.getInstance().with("Bluetooth", BlueBusEvent.class);
                toast("成功！");
            }
            super.onPostExecute(socket);
        }
    }

    protected void toast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    public void onConnected(BluetoothSocket socket, int taskType) {
        switch (taskType) {
            case Constant.TASK_TYPE_PRINT:
                OrderPar par = new OrderPar();
                par.setOrderNo(orderInfo.getParam().getID());
                EasyHttp.post(HttpConfig.getOrderDetail)
                        .cacheKey(HttpConfig.getOrderDetail)
                        .upJson(GsonUtils.toJson(par))
                        .execute(new SimpleCallBack<OrderListDetailModel>() {
                            @Override
                            public void onSuccess(OrderListDetailModel orderListDetailModel) {
                                PrintUtil.printTest(socket, orderListDetailModel, 0, order -> {

                                });
                            }

                            @Override
                            public void onError(ApiException e) {

                            }

                            @Override
                            public void onCompleted() {

                            }
                        });

                break;
            case Constant.TASK_TYPE_CONNECT:
                if (socket != null) {
                    Hawk.put("BluetoothName", device.getName());
                    Hawk.put("BluetoothDevice", device.getAddress());
                    acquireWakeLock();
                    if (tempList != null && tempList.size() != 0) {
                        connectDevice(tempList.get(0), order -> {
                            for (PrintOrderInfo info : tempList) {
                                if (info == null) {
                                    continue;
                                }
                                if (info.getParam().getID().equals(order)) {
                                    tempInfo = info;
                                    break;
                                }
                            }
                            tempList.remove(tempInfo);
                            if (tempList.size() != 0) {
                                connectDevice(tempList.get(0), OrderNo -> {
                                    for (PrintOrderInfo info : tempList) {
                                        if (info == null) {
                                            continue;
                                        }
                                        if (info.getParam().getID().equals(OrderNo)) {
                                            tempInfo = info;
                                            break;
                                        }
                                    }
                                    tempList.remove(tempInfo);
                                });
                            }
                        });
                    }
                }
                break;
            default:
                break;
        }
    }

    /**
     * 模拟心跳
     */
    private void sendHeart() {
        poolExecutor.execute(() -> {
            while (true) {
                byte buffer = 0;
                try {
                    outputStream.write(buffer);
                    outputStream.flush();
                    Thread.sleep(500);
                } catch (Exception e) {

                }
            }
        });
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void print(BlueEvent event) {
//        orderInfo = event.getInfo();
//        switch (event.getCode()) {
//            case Constant.TASK_TYPE_CONNECT:
//                if (event.getList() != null && event.getList().size() != 0) {
//                    tempList.addAll(event.getList());
//                } else {
//                    if (event.getInfo() != null) {
//                        tempList.add(event.getInfo());
//                    }
//                }
//                device = event.getDevice();
//                connectDevice(event.getDevice(), event.getCode());
//                break;
//            case Constant.TASK_TYPE_PRINT:
//                if (mSocket != null) {
//                    if (event.getInfo() != null) {
//                        tempList.add(event.getInfo());
//                    }
//                    if (device != null) {
//                        orderInfo = event.getInfo();
//                        connectDevice(device, event.getCode());
//                    }
//
////                    PrintUtil.printTestT(mSocket, null, order -> {
//
////                    });
//                }
//                break;
//            default:
//                break;
//        }
//    }

    /**
     * 发送socket
     */
    private void sendMsg() {
        poolExecutor.execute(() -> {

        });
    }

    /**
     * 断开连接
     */
    public void disconnect() {
        closeSocket();
        cancelConnectTask();
    }

    /**
     * 当服务被创建时调用.
     */
    @Override
    public void onCreate() {
//        initReceiver();
    }

    /**
     * 调用startService()启动服务时回调
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("start----------------->");
        return mStartMode;
    }

    /**
     * 通过bindService()绑定到服务的客户端
     */
    @Override
    public IBinder onBind(Intent intent) {
//        initReceiver();
        System.out.println("bind start----------------->");
        return mBinder;
    }

    /**
     * 通过unbindService()解除所有客户端绑定时调用
     */
    @Override
    public boolean onUnbind(Intent intent) {
        disconnect();
        System.out.println("unbind start----------------->");
        return mAllowRebind;
    }

    /**
     * 通过bindService()将客户端绑定到服务时调用
     */
    @Override
    public void onRebind(Intent intent) {

    }

    /**
     * 服务不再有用且将要被销毁时调用
     */
    @Override
    public void onDestroy() {
        disconnect();
        System.out.println("onDestroy start----------------->");
    }

    private PowerManager.WakeLock mWakeLock = null;

    /**
     * 获取唤醒锁
     */
    @SuppressLint("InvalidWakeLockTag")
    private void acquireWakeLock() {
        if (mWakeLock == null) {
            PowerManager mPM = (PowerManager) getSystemService(Context.POWER_SERVICE);
            mWakeLock = mPM.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "PlayService");
            if (mWakeLock != null) {
                mWakeLock.acquire();
            }
        }
    }

    /**
     * 释放锁
     */
    private void releaseWakeLock() {
        if (mWakeLock != null) {
            mWakeLock.release();
            mWakeLock = null;
        }
    }
}
